package com.syl.springcloud.starter.mybatis.component;

import com.syl.springcloud.starter.mybatis.annotation.DataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 *  动态数据源切换aop
 *  TODO 更改项目时需要更改aspect 方法Pointcut注解的service包
 * @author syl
 * @create 2018-08-29 17:20
 **/
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Order(-10) //保证该AOP在@Transactional之前执行
@Component
public class DataSourceAspect {
    private static Logger LOG = LoggerFactory.getLogger(DataSourceAspect.class);

    @Pointcut("execution(* com.syl.springcloud.*.*.service.*.*(..))")
    public void aspect() {}

    /**
     * 配置前置通知,使用在方法aspect()上注册的切入点
     */
    @Before("aspect()")
    public void before(JoinPoint point) {
        Class<?> aClass = point.getTarget().getClass();
        String className = aClass.getName();
//        String method = point.getSignature().getName();
        DataSource dataSource = aClass.getAnnotation(DataSource.class);
        if(dataSource == null)return;
        LOG.debug(className + "==============use "+ dataSource.value().getName() +"  datasource==============");
//        String className = point.getTarget().getClass().getName();
//        String method = point.getSignature().getName();
//        logger.info(className + "." + method + "(" + StringUtils.join(point.getArgs(), ",") + ")");
        DatabaseContextHolder.setDatabaseType(dataSource.value());

    }

    @After("aspect()")
    public void after(JoinPoint point) {
        DatabaseContextHolder.clear();
    }

}
